<template>
  <div ref="mapContainer" class="baidu-map-container"></div>
</template>

<script>
import { onMounted, ref } from 'vue'

export default {
  name: 'BaiduMap',
  props: {
    ak: {
      type: String,
      required: true
    },
    center: {
      type: Object,
      default: () => ({ lng: 116.184493, lat: 40.080566 })
    },
    zoom: {
      type: Number,
      default: 15
    }
  },
  setup(props) {
    const mapContainer = ref(null)
    let map = null

    const initMap = async () => {
      try {
        // 加载百度地图SDK
        await loadBMap(props.ak)
        
        // 创建地图实例
        map = new BMap.Map(mapContainer.value)
        
        // 设置中心点和缩放级别
        const point = new BMap.Point(props.center.lng, props.center.lat)
        map.centerAndZoom(point, props.zoom,18)
        
        // 启用滚轮缩放和平移
        map.enableScrollWheelZoom()
        map.enableDragging()
        
        // 添加控件
        map.addControl(new BMap.NavigationControl())
        map.addControl(new BMap.ScaleControl())
        
        // 添加标记
        const marker = new BMap.Marker(point)
        map.addOverlay(marker)
        
      } catch (error) {
        console.error('百度地图加载失败:', error)
      }
    }

    onMounted(() => {
      initMap()
    })

    return {
      mapContainer
    }
  }
}

// 加载百度地图SDK的函数
function loadBMap(ak) {
  return new Promise((resolve, reject) => {
    if (typeof BMap !== 'undefined') {
      resolve(BMap)
      return
    }
    
    window.onBMapCallback = function() {
      resolve(BMap)
    }
    
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=onBMapCallback`
    script.onerror = reject
    document.head.appendChild(script)
  })
}
</script>

<style>
.baidu-map-container {
  width: 100%;
  height: 100%;
  min-height: 250px;
}
</style>